package com.yuanlp.shoppingmall.home.adapter;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.youth.banner.Banner;
import com.youth.banner.Transformer;
import com.youth.banner.listener.OnBannerListener;
import com.youth.banner.loader.ImageLoader;
import com.yuanlp.shoppingmall.R;
import com.yuanlp.shoppingmall.activity.GoodsInfoActivity;
import com.yuanlp.shoppingmall.home.model.ResultBeanData;
import com.yuanlp.shoppingmall.utils.Constants;
import com.zhy.magicviewpager.transformer.ScaleInTransformer;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by 原立鹏 on 2017/8/14.
 */

public class HomeFragmentAdapter extends RecyclerView.Adapter {

    public static final int BANNER=0;  //横幅

    public static final int CHANNEL=1; //频道类型
    public static final int ACT=2; //活动类型
    public static final int SECKILL=3; //秒杀
    public static final int RECOMMEND=4; //推荐
    public static final int HOT=5; //热卖
    protected  Context context;
    private  ResultBeanData.ResultBean resultBean;
    /**
     * 秒杀倒计时的控件，写到这里是为了方便在主线程的handler来操作
     */
    TextView tv_time_seckill;
    /**
     * 秒杀倒计时
     */
    long dt=0;

    /**
     * 当前类型
     */
    private int currentType=0;
    private final LayoutInflater layoutInflater;

    public HomeFragmentAdapter(Context context, ResultBeanData.ResultBean resultBean) {
        this.context=context;
        this.resultBean=resultBean;

        /**
         * 加载布局文件的类对象
         */
        layoutInflater = LayoutInflater.from(context);
    }


    /**
     * 创建viewholder 相当于baseadapter里的getview，相当于viewholder部分代码
     * @param parent
     * @param viewType  当前的类型
     * @return  返回一个用来展示的控件的布局，如下方的R。layout.banner_viewpager这个布局的页面等
     */
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        if (viewType==BANNER){
            return new BannerViewHolder(context,layoutInflater.inflate(R.layout.banner_viewpager,null));
        }else if (viewType==CHANNEL){
            return new ChannelViewHolder(context,layoutInflater.inflate(R.layout.channel_item,null));
        }else if (viewType==ACT){
            return new ActViewHolder(context,layoutInflater.inflate(R.layout.act_item,null));
        }else if (viewType==SECKILL){  //秒杀
            return  new SeckillViewHolder(context,layoutInflater.inflate(R.layout.seckill_item,null));
        }else if (viewType==RECOMMEND){
            return new RecommendViewHolder(context,layoutInflater.inflate(R.layout.recomment_item,null));
        }else if (viewType==HOT){
            return new HotViewHolder(context, layoutInflater.inflate(R.layout.hot_item,null));
        }
        return null;
    }


    /**
     * 相当于getview里的绑定数据
     * @param holder
     * @param position
     */
    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {

        //通过position，来获取当前是哪个类型
        if (getItemViewType(position)==BANNER){
            //是banner类型，将holder强转为bannerviewholder
            BannerViewHolder bannerViewHolder= (BannerViewHolder) holder;
            bannerViewHolder.setData(resultBean.getBanner_info());
        }else if (getItemViewType(position)==CHANNEL){
            ChannelViewHolder channelViewHolder= (ChannelViewHolder) holder;
            channelViewHolder.setData(resultBean.getChannel_info());
        }else if (getItemViewType(position)==ACT){
            ActViewHolder actviewholder= (ActViewHolder) holder;
            actviewholder.setData(resultBean.getAct_info());
        }else if (getItemViewType(position)==SECKILL){  //秒杀
            SeckillViewHolder seckillViewHolder= (SeckillViewHolder) holder;
            seckillViewHolder.setData(resultBean.getSeckill_info());
        }else if (getItemViewType(position)==RECOMMEND){
            RecommendViewHolder recommendViewHolder= (RecommendViewHolder) holder;
            recommendViewHolder.setData(resultBean.getRecommend_info());
        }else if (getItemViewType(position)==HOT){
            HotViewHolder hotViewHolder= (HotViewHolder) holder;
            hotViewHolder.setData(resultBean.getHot_info());
        }
    }

    class HotViewHolder extends RecyclerView.ViewHolder{

        TextView tv_more_hot;
        GridView gv_hot;

        public HotViewHolder(Context context, View inflate) {
            super(inflate);
            tv_more_hot= (TextView) inflate.findViewById(R.id.tv_more_hot);
            gv_hot= (GridView) inflate.findViewById(R.id.gv_hot);

            gv_hot.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    //点击后跳转到详情页面
                    startGoodsInfoActivity();
                }
            });
        }

        public void setData(List<ResultBeanData.ResultBean.HotInfoBean> hot_info) {
            HotAdapter adapter=new HotAdapter(context,hot_info);
            gv_hot.setAdapter(adapter);
        }
    }

    /**
     * 推荐的viewholder
     */
    class RecommendViewHolder extends RecyclerView.ViewHolder{
        TextView tv_more_remommend;
        GridView gv_commend;

        public RecommendViewHolder(final Context context, View inflate) {
            super(inflate);
            tv_more_remommend= (TextView) inflate.findViewById(R.id.tv_more_remommend);
            gv_commend= (GridView) inflate.findViewById(R.id.gv_commend);
            gv_commend.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    Toast.makeText(context, "position=="+position, Toast.LENGTH_SHORT).show();
                    //点击后跳转到详情页面
                    startGoodsInfoActivity();
                }
            });
        }

        public void setData(List<ResultBeanData.ResultBean.RecommendInfoBean> recommend_info) {
            RecommendAdapter adapter=new RecommendAdapter(context,recommend_info);
            gv_commend.setAdapter(adapter);
        }
    }

    /**
     * 秒杀的viewholder
     */
    class SeckillViewHolder extends RecyclerView.ViewHolder{
        /**
         * 初始化布局中的控件
         */

        TextView tv_more_seckill;
        RecyclerView rv_seckill;
        SeckillViewHolderAdapter seckillViewHolderAdapter;

        protected Handler handler=new Handler(){


            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);

                    dt=dt-1000;
                /**
                 * 这里一定要注意引入的包是java。text而不是import com.ibm.icu.text.SimpleDateFormat;
                 */
                java.text.SimpleDateFormat formatter=new java.text.SimpleDateFormat("HH:mm:ss");
                String time = formatter.format(new Date(dt));
                tv_time_seckill.setText(time);



                        handler.removeMessages(0);

                        handler.sendEmptyMessageDelayed(0,1000);  //给handler发消息


                    if (dt<=0){
                        handler.removeCallbacksAndMessages(null); //移除所有消息
                    }


            }
        };


        /**
         * 构造函数，对应上面传入的参数
         * @param context
         * @param view
         */
        public SeckillViewHolder(Context context,View view){
            super(view);
            /**
             * 实例化控件
             */
            tv_time_seckill= (TextView) view.findViewById(R.id.tv_time_seckill);
            tv_more_seckill= (TextView) view.findViewById(R.id.tv_more_seckill);
            rv_seckill= (RecyclerView) view.findViewById(R.id.rv_seckill);

        }

        public void setData(ResultBeanData.ResultBean.SeckillInfoBean seckill_info) {
            //1、得到数据
            //2、设置数据：文本和recycleview的数据
            seckillViewHolderAdapter=new SeckillViewHolderAdapter(context,seckill_info.getList());
            rv_seckill.setAdapter(seckillViewHolderAdapter);

            //要想recycleviewView起作用，还要设置管理器
            /**
             * 参数说明，第一个是上下文，第二个是方向：目前是水平方向，第三个是否采用倒序
             */
            rv_seckill.setLayoutManager(new LinearLayoutManager(context,LinearLayoutManager.HORIZONTAL,false));

            seckillViewHolderAdapter.setOnSeckillRecyclerView(new SeckillViewHolderAdapter.OnSeckillRecyclerView() {
                @Override
                public void onItemClick(int position) {
                    Toast.makeText(context,"秒杀"+position,Toast.LENGTH_SHORT).show();
                    //点击后跳转到详情页面
                    startGoodsInfoActivity();
                }
            });

            dt=Integer.valueOf(seckill_info.getEnd_time())-Integer.valueOf(seckill_info.getStart_time());
            System.out.println("剩余时间是："+dt);
           handler.sendEmptyMessageDelayed(0,1000);
        }


    }

    /**
     * 活动适配器
     */
    class ActViewHolder extends RecyclerView.ViewHolder {
         private ViewPager act_viewpager;
        public ActViewHolder(Context context, View inflate) {
            super(inflate);
            act_viewpager= (ViewPager) inflate.findViewById(R.id.act_viewpager);

        }


         public void setData(final List<ResultBeanData.ResultBean.ActInfoBean> act_info) {
             act_viewpager.setPageMargin(30);
             act_viewpager.setOffscreenPageLimit(3);
             //设置viewpager的切换效果，利用的是github的magicviewpager插件
             act_viewpager.setPageTransformer(true,new ScaleInTransformer());
             /**
              * 设置viewpager的适配器，至少要重写下方的四个方法
              */
             act_viewpager.setAdapter(new PagerAdapter() {

                 @Override
                 public int getCount() {
                     return act_info.size();
                 }

                 /**
                  * 确认2者是不是相同
                  * @param view 页面
                  * @param object  instantiateItem方法返回的值
                  * @return
                  */
                 @Override
                 public boolean isViewFromObject(View view, Object object) {
                     return view==object;
                 }

                 /**
                  *
                  * @param container  这个其实就是viewpager自身
                  * @param position    对应页面的位置
                  * @return
                  */
                 @Override
                 public Object instantiateItem(ViewGroup container, int position) {
                     ImageView imageView=new ImageView(context);
                     imageView.setScaleType(ImageView.ScaleType.FIT_XY);  //设置imageview的拉伸，xy轴都拉伸
                    //远程加载imageview的图片
                    Glide.with(context).load(Constants.IMG_URL+act_info.get(position).getIcon_url()).into(imageView);

                     //将图片添加到容器中
                     container.addView(imageView);

                     imageView.setOnClickListener(new View.OnClickListener() {
                         @Override
                         public void onClick(View v) {
                             Toast.makeText(context, "点击了图片", Toast.LENGTH_SHORT).show();
                         }
                     });
                     return imageView;
                 }

                 /**
                  * 移除图片
                  * @param container
                  * @param position
                  * @param object
                  */
                 @Override
                 public void destroyItem(ViewGroup container, int position, Object object) {
                    container.removeView((View) object);
                 }
             });
         }
     }

    class ChannelViewHolder extends RecyclerView.ViewHolder{
        private GridView gv_channel;

        public ChannelViewHolder(final Context context, View itemView) {
            super(itemView);
            gv_channel= (GridView) itemView.findViewById(R.id.gv_channel);

            gv_channel.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    Toast.makeText(context,"position是"+position,Toast.LENGTH_SHORT).show();
                }
            });

        }

        public void setData(List<ResultBeanData.ResultBean.ChannelInfoBean> channel_info) {

            //这里得到数据了，然后设置GridView的适配器
            ChannelAdapter adapter=new ChannelAdapter(context,channel_info);
            gv_channel.setAdapter(adapter);

        }
    }

    /**
     *  横幅的viewholder
     *  所有类型的viewholder都要继承recycleview的viewholder
     */
    class BannerViewHolder extends RecyclerView.ViewHolder{

        private Context context;
        private View view;
        private Banner banner;  //banner_viewpager里的banner控件id

        /**
         * 构造方法，实例化其中的参数
         * @param context
         * @param inflate
         */
        public BannerViewHolder(Context context, View inflate) {
            super(inflate);
            this.context=context;
            this.view=inflate;
            banner= (Banner) view.findViewById(R.id.banner);
        }

        public void setData(List<ResultBeanData.ResultBean.BannerInfoBean> banner_info) {

            //通过banner的setimages来绑定数据
            List<String> imagesUrl=new ArrayList<>();
            for (ResultBeanData.ResultBean.BannerInfoBean bannerInfoBean:banner_info){
                String imageurl=bannerInfoBean.getImage();  //这个路径是例如： /14782094.jpg这样子的路径，需要在前面加上图片的根路径
                imagesUrl.add(Constants.IMG_URL+imageurl);
            }

            banner.setImageLoader(new ImageLoader() {
                @Override
                public void displayImage(Context context, Object path, ImageView imageView) {
                    Glide.with(context).load(path).into(imageView);  //使用glide来加载远程图片
                }
            });
            banner.setImages(imagesUrl);
            banner.setDelayTime(3000);
            banner.setBannerAnimation(Transformer.Accordion);// 设置banner切换的动画效果
            banner.start();

            /**
             * 设置图片的点击事件，当点击图片时，会回调下面的方法。
             */
            banner.setOnBannerListener(new OnBannerListener() {
                @Override
                public void OnBannerClick(int position) {
                    Toast.makeText(context,"position是+"+position,Toast.LENGTH_SHORT).show();

                    //点击后跳转到详情页面
                    startGoodsInfoActivity();
                }
            });
        }
    }

    /**
     * 启动跳转到详情的页面
     */
    private void startGoodsInfoActivity() {
        System.out.println("点击后准备跳转");
        Intent intent=new Intent(context, GoodsInfoActivity.class);
        context.startActivity(intent);
    }


    /**
     * 总共多少条数据
     * @return
     */
    @Override
    public int getItemCount() {
        /**
         * 开发过程中从1到6
         */
        return 6;
    }

    /**
     * 获取类型
     * @param position
     * @return
     */
    @Override
    public int getItemViewType(int position) {

        //根据位置不同，获取不同的类型
        switch (position){
            case BANNER:
                currentType=BANNER;
                break;
            case CHANNEL:
                currentType=CHANNEL;
                break;
            case SECKILL:
                currentType=SECKILL;
                break;
            case RECOMMEND:
                currentType=RECOMMEND;
                break;
            case HOT:
                currentType=HOT;
                break;
            case ACT:
                currentType=ACT;
                break;
        }
        return currentType;
    }


}
